#ifndef SOLUTION_H_
#define SOLUTION_H_
#include <algorithm>
#include <vector>
using namespace std;

 struct Interval 
 {
     int start;
     int end;
     Interval() : start(0), end(0) {}
     Interval(int s, int e) : start(s), end(e) {}
	  
 };
 
 struct IntervalComp
 {
	 bool operator()(const Interval& v1, const Interval& v2)
	 {
		 return (v1.start==v2.start)?(v1.end<=v2.end):(v1.start<v2.start);
	 }

	 bool intersects(const Interval& a,const Interval& b)
	 {
		 return !((a.end<b.start) || (a.start>b.end)); 
	 }

	 void merge(Interval& a, const Interval& b)
	 {
		 a.start = min(a.start,b.start);
		 a.end = max(a.end,b.end);
	 }
 };
class Solution 
{
public:
    vector<Interval> merge(vector<Interval> &intervals)
	{
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
		vector<Interval> results;
		if(intervals.empty())
			return results;

		IntervalComp comp;
		sort(intervals.begin(),intervals.end(),comp);
		results.push_back(intervals[0]);

		for(size_t i=1;i<intervals.size();i++)
		{
			Interval& last = results.back();
			if(comp.intersects(last,intervals[i]))
			{
				comp.merge(last,intervals[i]);
			}
			else
			{
				results.push_back(intervals[i]);
			}
		}

		return results;
    }
};
#endif
